package org.firefly.fx.service.websocket;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.firefly.fx.constants.ConfigInfo;
import org.firefly.fx.service.common.IWebsocketSessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * 握手前判断httpSession权限
 * @author firefly
 */

@Service("webSocketHandshakeInterceptor")
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
	@Autowired private IWebsocketSessionService wssSerivce ;
	@Override
	public boolean beforeHandshake(ServerHttpRequest request,ServerHttpResponse response, WebSocketHandler wsHandler,Map<String, Object> attributes) throws Exception {
		if (!(request instanceof ServletServerHttpRequest) || !(response instanceof ServletServerHttpResponse)) {
			return false;
		}
		
		ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
		HttpSession session = servletRequest.getServletRequest().getSession();
		
		//未登录，跳转到登录页面
		if(session==null){
			ServletServerHttpResponse servletResponse = (ServletServerHttpResponse) response;
			servletResponse.getServletResponse().sendRedirect(ConfigInfo.URL_LOGIN);
			return false;
		}
		
		Object userId = session.getAttribute(ConfigInfo.USER_ID);
		if(userId==null){
			ServletServerHttpResponse servletResponse = (ServletServerHttpResponse) response;
			servletResponse.getServletResponse().sendRedirect(ConfigInfo.URL_LOGIN);
			return false;
		}
		
		//已连接
		if(wssSerivce.isOnline((String)userId)){
			wssSerivce.sendMsgToUser((String)userId,"您已经连接，且尝试再次连接，请查明详情。");
			return false;
		}
		
		
		attributes.put(ConfigInfo.USER_ID, userId);

		return true;
	}

	@Override
	public void afterHandshake(ServerHttpRequest request,
			ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception exception) {

	}
}
